#-*- encoding: utf-8 -*-

import web
import json
from objects.entity import Entity

def json_encode(func):
    """
    Декоратор для вывода всех данных в JSON
    @return func
    """
    def encode(*args, **kwargs):
        result = func(*args, **kwargs)
        if isinstance(result, Entity):
            return result.serialize()
        return json.dumps(result)
    return encode

# Производит обработку запросов к API
class HandleApi:
    __handlers = {}
    app = None

    @json_encode
    def GET(self):
        input = web.input(_unicode=False)
        if ('action' not in input) or (input.action not in HandleApi.__handlers):
            return { 'error': 'InvalidAction' }
        return HandleApi.__handlers[input.action].run(HandleApi.app, input)

    @staticmethod
    def add_handler(action, handler_class):
		HandleApi.__handlers[action] = handler_class()
